#include "QuinceApplication.h"
#include "SketchDocument.h"
#include "MainWindow.h"
#include "MessageDispatcher.h"
#include "MessageListener.h"
#include "CreateDocument.h"

QuinceApplication *QuinceApplication::self = NULL;

namespace {
    inline void addListener(MessageDispatcher &dispatcher, MessageListener *listener) {
        dispatcher.subscribe(listener->listeningCodes(), listener);
    }
}

QuinceApplication::QuinceApplication(int argc, char**argv)
    : QApplication(argc, argv)
{
    self = this;
    mMsgDispatcher.reset(new MessageDispatcher);
    addListener(*mMsgDispatcher, new CreateDocument);
}

QuinceApplication::~QuinceApplication()
{
    self = NULL;
}

QuinceApplication *
QuinceApplication::instance()
{
    return self;
}

void
QuinceApplication::addDocument(SketchDocument * doc)
{
    mDocuments.push_back(doc);
    QWidget *mdi = MainWindow::instance()->createMdiChild();
    mdi->show();
}

void
QuinceApplication::removeDocument(SketchDocument * doc)
{
    if (doc != NULL) {
        mDocuments.remove(doc);
    }
}

MessageDispatcher &
QuinceApplication::localDispatcher() const
{
    assert(mMsgDispatcher.get() != NULL);
    return *mMsgDispatcher;
}
